package com.sun.controller;

import com.alibaba.fastjson.JSON;
import com.sun.entity.Book;
import com.sun.entity.Borrow;
import com.sun.entity.Fine;
import com.sun.entity.Reader;
import com.sun.service.BookService;
import com.sun.service.BorrowService;
import com.sun.service.FineService;
import com.sun.service.ReaderService;
import com.sun.util.BorrowUtil;
import jakarta.servlet.http.HttpServlet;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * @author SunRui
 * @description TODO
 * @date 2024/8/10 22:31
 */

@Controller
@RequestMapping("/BorrowController")
public class BorrowController{
    @Autowired
    private BorrowService borrowService;
    @Autowired
    private ReaderService readerService;
    @Autowired
    private BookService bookService;
    @Autowired
    private FineService fineService;
    private static Logger logger = Logger.getLogger(BookController.class);
    private String jsonString;
    private String str;

    @RequestMapping("/borrowBookTs")
    public void borrowBookTs(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //借阅
        //接收传回要借阅的暂存架图书code
        HttpSession session = req.getSession();
        String elBookTs = req.getParameter("bookIds");
        elBookTs = elBookTs.substring(1, elBookTs.length() - 1);
        String[] eliminateBookTs = elBookTs.split(",");
        List<String> elBootTsId = new ArrayList<>();
        for (String bookId : eliminateBookTs) {
            elBootTsId.add(bookId.replace("\"", ""));
        }
        logger.debug("借阅书籍code:" + elBootTsId);
        //获取借阅人ID
        Reader reader = (Reader) session.getAttribute("reader");
        int readerId = reader.getId();
        //查看借阅人是否还剩足够的借阅数借阅图书
        if (readerService.selectBorrowSum(readerId)>=elBootTsId.size()){
            if (readerService.deductBorrowSum(readerId,elBootTsId.size())>0){
                List<Book> bookList = new ArrayList<>();
                for (String bookCode : elBootTsId) {
                    //通过code返回书籍信息
                    Book book = bookService.bookTs(bookCode);
                    bookList.add(book);
                }
                logger.debug("借阅书籍信息:" + bookList.toString());
                List<Borrow> borrowList = new ArrayList<>();
                BorrowUtil borrowUtil = new BorrowUtil();
                for (Book book : bookList) {
                    Borrow borrow = new Borrow();
                    String borrowDate = borrowUtil.getCurrentDate();
                    borrow.setBorrowDate(borrowDate);
                    borrow.setBookId(book.getId());
                    borrow.setReaderId(readerId);
                    borrowList.add(borrow);
                    //更改书籍状态
                    bookService.setBookSatus(book.getId(), 2);
                }
                if (borrowService.addBorrow(borrowList) > 0) {
                    //获取缓存架数据进行清除操作
                    List<String> eliminateCodeArray = (List<String>) session.getAttribute("codeArray");
                    logger.debug("elBootTsId:" + elBootTsId.toString());
                    logger.debug("eliminateCodeArray:" + eliminateCodeArray.toString());
                    if (eliminateCodeArray != null) {
                        for (String bookId : elBootTsId) {
                            if (eliminateCodeArray.contains(bookId)) {
                                eliminateCodeArray.remove(bookId);
                            }
                        }
                        session.setAttribute("codeArray", eliminateCodeArray);
                        str = "ok";
                    }
                }
                logger.debug("清除结束(codeArray)：" + (List<String>) session.getAttribute("codeArray"));
            }
        }else {
            str = "noBookNum";
        }

        jsonString = JSON.toJSONString(str);
        resp.getWriter().write(jsonString);
    }

    @RequestMapping("/borrowBookTsShow")
    public void borrowBookTsShow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //加载借阅架
        //获取借阅人ID
        HttpSession session = req.getSession();
        Reader reader2 = (Reader) session.getAttribute("reader");
        int readerId2 = reader2.getId();
        List<Borrow> borrows = borrowService.getBorrow(readerId2, 0);
        for (Borrow b : borrows) {
            int bookId = b.getBookId();
            Book book = bookService.getBook(bookId);
            b.setBookName(book.getName());
        }
        jsonString = JSON.toJSONString(borrows);
        resp.getWriter().write(jsonString);
    }

    @RequestMapping("/borrowBookTsOne")
    public void borrowBookTsOne(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        // 借阅1本书
        String code = req.getParameter("code");
        //获取借阅人ID
        Reader reader3 = (Reader) session.getAttribute("reader");
        int readerId3 = reader3.getId();
        if (readerService.selectBorrowSum(readerId3)>=1){
            readerService.deductBorrowSum(readerId3,1);
            List<Book> bookList1 = new ArrayList<>();
            //通过code返回书籍信息
            Book book = bookService.bookTs(code);
            bookList1.add(book);
            logger.debug("借阅书籍信息:" + bookList1.toString());
            List<Borrow> borrowList1 = new ArrayList<>();
            BorrowUtil borrowUtil = new BorrowUtil();
            for (Book book1 : bookList1) {
                Borrow borrow = new Borrow();
                String borrowDate = borrowUtil.getCurrentDate();
                borrow.setBorrowDate(borrowDate);
                borrow.setBookId(book1.getId());
                borrow.setReaderId(readerId3);
                borrowList1.add(borrow);
                //更改书籍状态
                bookService.setBookSatus(book.getId(), 2);
            }
            if (borrowService.addBorrow(borrowList1) > 0) {
                //获取缓存架数据进行清除操作
                List<String> eliminateCodeArray = (List<String>) session.getAttribute("codeArray");
                if (eliminateCodeArray == null) {
                    eliminateCodeArray = new ArrayList<>();
                }
                logger.debug("OneCode:" + code);
                logger.debug("eliminateCodeArray:" + eliminateCodeArray.toString());

                if (eliminateCodeArray != null) {
                    if (eliminateCodeArray.contains(code)) {
                        eliminateCodeArray.remove(code);
                    }
                    session.setAttribute("codeArray", eliminateCodeArray);
                    str = "ok";
                }
            }
            logger.debug("清除结束(codeArray)：" + (List<String>) session.getAttribute("codeArray"));
        }else {
            str = "noBookNum";
        }

        jsonString = JSON.toJSONString(str);
        resp.getWriter().write(jsonString);
    }

    @RequestMapping("/borrowRenew")
    public void borrowRenew(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int borrowId = Integer.parseInt(req.getParameter("borrowId"));
        int renewDays = Integer.parseInt(req.getParameter("renewDay"));
        logger.debug("续借ID："+borrowId+"续借天数："+renewDays);
        if (borrowService.updateRenewDays(renewDays,borrowId)>0){
            str = "ok";
        }
        jsonString = JSON.toJSONString(str);
        resp.getWriter().write(jsonString);
    }

    @RequestMapping("/returnBook")
    public void returnBook(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        // 还书
        // 通过传回的ID查询借阅信息
        int borrowIds = Integer.parseInt(req.getParameter("borrowId"));
        logger.debug("还书的ID:"+borrowIds);
        Borrow returnBorrow = borrowService.getBorrowById(borrowIds);
        logger.debug("归还书的信息:"+returnBorrow.toString());
        Reader reader5 = (Reader) session.getAttribute("reader");
        int readerId5 = reader5.getId();
        //将借阅天数和续借天数相加，查看是否超过时间需要还款
        int borrowDays = returnBorrow.getBorrowDays();
        int renewDays2 = returnBorrow.getRenewDays();
        String borrowDate = returnBorrow.getBorrowDate();
        int totalDays = borrowDays + renewDays2;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime borrowDateObj = LocalDateTime.parse(borrowDate, formatter);
        LocalDateTime dueDate = borrowDateObj.plusDays(totalDays);
        LocalDateTime now = LocalDateTime.now();
        int bookId = returnBorrow.getBookId();
        //将bookId和borrowIds存储到Session方便还款的时候调用
        session.setAttribute("fineAmountBookId",bookId);
        session.setAttribute("fineAmountBorrowIds",borrowIds);
        BorrowUtil borrowUtil = new BorrowUtil();
        if (dueDate.isAfter(now)) {
            System.out.println("未超过还款日期");
            //将书籍状态改成在库,并将归还状态改成1
            borrowService.updateBack(borrowIds);
            bookService.setBookSatus(bookId,1);
            //将可借阅书籍数量+1
            readerService.addBorrowSum(readerId5,1);
            str = "ok";//还书成功
        } else {
            logger.debug("ID:"+borrowIds+"超过还款日期，需要罚款！");
            //计算罚款金额
            float fineAmount = 0;
            try {
                logger.debug("借书日期："+dueDate.format(formatter)+";结束日期："+ now.format(formatter));
                fineAmount = borrowUtil.calculateFine(now.format(formatter),dueDate.format(formatter));
            } catch (ParseException e) {
                logger.debug(e);
            }
            logger.debug("罚款金额:"+fineAmount);
            //将罚款金额先暂时存储到Session中
            session.setAttribute("fineAmount", fineAmount);

            str = "因为超出还书日期，需缴纳罚款："+fineAmount;
        }
        jsonString = JSON.toJSONString(str);
        resp.getWriter().write(jsonString);
    }

    @RequestMapping("/fineAmount")
    public void fineAmount(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        // 还款
        float fineAmounts = (float) session.getAttribute("fineAmount");
        logger.debug("需要还款金额："+fineAmounts);
        // 获取当前用户有多少钱
        Reader reader4 = (Reader) session.getAttribute("reader");
        float money = reader4.getMoney();
        //从session中提取数据进行还书
        int fineAmountBookId = (int) session.getAttribute("fineAmountBookId");
        int fineAmountBorrowIds = (int) session.getAttribute("fineAmountBorrowIds");
        Fine fine;
        if (money >= fineAmounts){
            logger.debug("用户的金额大于等于需要还款的金额");
            //进行扣钱操作
            readerService.updateMoney(fineAmounts,reader4.getId());
            //进行增加可借阅书数量操作
            readerService.addBorrowSum(reader4.getId(),1);
            //将书籍状态改成在库,并将归还状态改成1
            borrowService.updateBack(fineAmountBorrowIds);
            bookService.setBookSatus(fineAmountBookId,1);
            //添加罚款记录
            fine = new Fine();
            fine.setBorrowId(fineAmountBorrowIds);
            fine.setReaderId(reader4.getId());
            fine.setBookId(fineAmountBookId);
            fine.setAmount(fineAmounts);
            DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime now2 = LocalDateTime.now();
            fine.setPaidDate(now2.format(formatter2));
            fine.setStaus(1);
            fineService.addFine(fine);

            str = "ok";//还书成功
        }else {
            logger.debug("用户的金额远远达不到还款金额");
            str = "no";
        }
        jsonString = JSON.toJSONString(str);
        resp.getWriter().write(jsonString);
    }

    @RequestMapping("/borrowHistoryTabShow")
    public void borrowHistoryTabShow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //借阅历史查询
        HttpSession session = req.getSession();
        Reader reader1 = (Reader) session.getAttribute("reader");
        int page = Integer.parseInt(req.getParameter("page"));
        List<com.sun.entity.BorrowUtil> borrowUtils = borrowService.getBorrowUtilList(reader1.getId(),((page-1)*5));
        jsonString = JSON.toJSONString(borrowUtils);
        resp.getWriter().write(jsonString);
    }

    @RequestMapping("/borrowHistoryPageShow")
    public void borrowHistoryPageShow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取借阅历史查询的总页数
        //获取总页数
        HttpSession session = req.getSession();
        Reader reader = (Reader) session.getAttribute("reader");
        int readerId = reader.getId();
        int allPage = borrowService.getAllPage(readerId);
        int pages;
        if (allPage%5>0){
            pages = (allPage/5)+1;
        }else {
            pages = allPage/5;
        }
        jsonString = JSON.toJSONString(pages);
        resp.getWriter().write(jsonString);
    }
}
